package com.bainuo.doctor.common.base;

import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.view.ViewGroup;

import static com.bainuo.doctor.common.base.NormalAdapterWrapper.ITEM_TYPE.NORMAL;


/**
 * Description:在normalAdapter基础上封装，添加header\footer，与normalAdapter进行解耦
 * Created by MonkeyShen on 2017/1/26.
 * Mail:shenminjie92@sina.com
 */
public class NormalAdapterWrapper extends RecyclerView.Adapter<RecyclerView.ViewHolder> {

    enum ITEM_TYPE {
        HEADER,
        FOOTER,
        NORMAL
    }

    private NormalAdapter mAdapter;
    private View mHeaderView;
    private View mFooterView;

    public NormalAdapterWrapper(NormalAdapter adapter) {
        mAdapter = adapter;
    }

    @Override
    public int getItemViewType(int position) {
        if (hasHeaderView() && position == 0) {
            return ITEM_TYPE.HEADER.ordinal();
        } else if (hasFooterView() && position == mAdapter.getItemCount() + 1) {
            return ITEM_TYPE.FOOTER.ordinal();
        } else {
            return NORMAL.ordinal();
        }
    }

    @Override
    public int getItemCount() {
        //根据header、footer进行设置
        int count = mAdapter.getItemCount();
        if (hasHeaderView()) {
            count++;
        }
        if (hasFooterView()) {
            count++;
        }
        return count;
    }

    @Override
    public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
        if (hasHeaderView() && position == 0) {
            return;
        } else if (hasFooterView() && position == mAdapter.getItemCount() + 1) {
            return;
        } else {
            mAdapter.onBindViewHolder(((NormalViewHolder) holder), mHeaderView != null ? position - 1 : position);
        }
    }

    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        if (viewType == ITEM_TYPE.HEADER.ordinal()) {
            return new RecyclerView.ViewHolder(mHeaderView) {
            };
        } else if (viewType == ITEM_TYPE.FOOTER.ordinal()) {
            return new RecyclerView.ViewHolder(mFooterView) {
            };
        } else {
            return mAdapter.onCreateViewHolder(parent, viewType);
        }
    }

    /**
     * 设置头部view
     *
     * @param view
     */
    public void setHeaderView(View view) {
        this.mHeaderView = view;
    }

    /**
     * 设置底部view
     *
     * @param view
     */
    public void setFooterView(View view) {
        this.mFooterView = view;
    }

    /**
     * 是否有头部view
     *
     * @return
     */
    public boolean hasHeaderView() {
        return mHeaderView != null;
    }

    /**
     * 是否有底部view
     *
     * @return
     */
    public boolean hasFooterView() {
        return mFooterView != null;
    }
}
